using Microsoft.AspNetCore.Mvc;
using System.Data;
using Dapper;
using Admin2025.Application.Dtos;

namespace Admin2025.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
  private readonly IDbConnection _db;

  public UserController(IDbConnection db)
  {
    _db = db;
  }

  // 分页获取用户
  [HttpGet("paged")]
  public async Task<IActionResult> GetPaged([FromQuery] int page = 1, [FromQuery] int pageSize = 10)
  {
    if (page < 1) page = 1;
    if (pageSize < 1) pageSize = 10;

    var sql = @"
        SELECT Id, Username, Nickname, AvatarUrl, IsActived AS IsEnabled
        FROM AppUser
        ORDER BY Id
        OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY;
        SELECT COUNT(1) FROM AppUser;
    ";

    var offset = (page - 1) * pageSize;
    using var multi = await _db.QueryMultipleAsync(sql, new { Offset = offset, PageSize = pageSize });
    var users = (await multi.ReadAsync<UserDto>()).ToList();
    var total = await multi.ReadFirstAsync<int>();

    return Ok(new
    {
      Data = users,
      Total = total,
      Page = page,
      PageSize = pageSize
    });
  }

  // 获取所有用户
  [HttpGet]
  public async Task<IActionResult> GetAll()
  {
    var sql = "SELECT Id, Username, Nickname, AvatarUrl, IsActived AS IsEnabled FROM AppUser";
    var users = await _db.QueryAsync<UserDto>(sql);
    return Ok(users);
  }

  // 获取用户详情
  [HttpGet("{id}")]
  public async Task<IActionResult> GetById(Guid id)
  {
    var sql = "SELECT Id, Username, Nickname, AvatarUrl, IsActived AS IsEnabled FROM AppUser WHERE Id = @Id";
    var user = await _db.QueryFirstOrDefaultAsync<UserDto>(sql, new { Id = id });
    if (user == null) return NotFound();
    return Ok(user);
  }

  // 创建用户
  [HttpPost]
  public async Task<IActionResult> Create([FromBody] CreateUserDto dto)
  {
    var salt = Guid.NewGuid().ToString("N");
    var pwdHash = HashPassword(dto.Password, salt);
    var sql = "INSERT INTO AppUser (Id, Username, Password, Salt, IsActived) VALUES (@Id, @Username, @Password, @Salt, 1)";
    var id = Guid.NewGuid();
    await _db.ExecuteAsync(sql, new { Id = id, Username = dto.Username, Password = pwdHash, Salt = salt });
    return Ok();
  }

  // 更新用户
  [HttpPut("{id}")]
  public async Task<IActionResult> Update(Guid id, [FromBody] UpdateUserDto dto)
  {
    var sql = "UPDATE AppUser SET Nickname = @Nickname, AvatarUrl = @AvatarUrl WHERE Id = @Id";
    await _db.ExecuteAsync(sql, new { Id = id, Nickname = dto.Nickname, AvatarUrl = dto.AvatarUrl });
    return Ok();
  }

  // 删除用户
  [HttpDelete("{id}")]
  public async Task<IActionResult> Delete(Guid id)
  {
    var sql = "DELETE FROM AppUser WHERE Id = @Id";
    await _db.ExecuteAsync(sql, new { Id = id });
    return Ok();
  }

  // 启用用户
  [HttpPost("{id}/enable")]
  public async Task<IActionResult> Enable(Guid id)
  {
    var sql = "UPDATE AppUser SET IsActived = 1 WHERE Id = @Id";
    await _db.ExecuteAsync(sql, new { Id = id });
    return Ok();
  }

  // 禁用用户
  [HttpPost("{id}/disable")]
  public async Task<IActionResult> Disable(Guid id)
  {
    var sql = "UPDATE AppUser SET IsActived = 0 WHERE Id = @Id";
    await _db.ExecuteAsync(sql, new { Id = id });
    return Ok();
  }

  // 分配角色
  [HttpPost("{userId}/roles/{roleId}")]
  public async Task<IActionResult> AssignRole(Guid userId, Guid roleId)
  {
    var sql = "INSERT INTO AppUserRole (UserId, RoleId) VALUES (@UserId, @RoleId)";
    await _db.ExecuteAsync(sql, new { UserId = userId, RoleId = roleId });
    return Ok();
  }

  // 移除角色
  [HttpDelete("{userId}/roles/{roleId}")]
  public async Task<IActionResult> RemoveRole(Guid userId, Guid roleId)
  {
    var sql = "DELETE FROM AppUserRole WHERE UserId = @UserId AND RoleId = @RoleId";
    await _db.ExecuteAsync(sql, new { UserId = userId, RoleId = roleId });
    return Ok();
  }

  // 更新头像
  [HttpPut("{userId}/avatar")]
  public async Task<IActionResult> UpdateAvatar(Guid userId, [FromBody] string avatarUrl)
  {
    var sql = "UPDATE AppUser SET AvatarUrl = @AvatarUrl WHERE Id = @UserId";
    await _db.ExecuteAsync(sql, new { UserId = userId, AvatarUrl = avatarUrl });
    return Ok();
  }

  // 更新昵称
  [HttpPut("{userId}/nickname")]
  public async Task<IActionResult> UpdateNickname(Guid userId, [FromBody] string nickname)
  {
    var sql = "UPDATE AppUser SET Nickname = @Nickname WHERE Id = @UserId";
    await _db.ExecuteAsync(sql, new { UserId = userId, Nickname = nickname });
    return Ok();
  }

  // 修改密码
  [HttpPut("{userId}/password")]
  public async Task<IActionResult> ChangePassword(Guid userId, [FromBody] ChangePasswordDto dto)
  {
    var user = await _db.QueryFirstOrDefaultAsync<dynamic>("SELECT Password, Salt FROM AppUser WHERE Id = @Id", new { Id = userId });
    if (user == null) return NotFound("用户不存在");
    var oldHash = HashPassword(dto.OldPassword, user.Salt);
    if (oldHash != user.Password) return BadRequest("原密码错误");
    var newHash = HashPassword(dto.NewPassword, user.Salt);
    var sql = "UPDATE AppUser SET Password = @Password WHERE Id = @Id";
    await _db.ExecuteAsync(sql, new { Password = newHash, Id = userId });
    return Ok();
  }

  // 密码加密方法
  private string HashPassword(string pwd, string salt)
  {
    using var sha256 = System.Security.Cryptography.SHA256.Create();
    var bytes = System.Text.Encoding.UTF8.GetBytes(pwd + salt);
    var hash = sha256.ComputeHash(bytes);
    return Convert.ToBase64String(hash);
  }
}

// ChangePasswordDto 示例
public class ChangePasswordDto
{
  public string OldPassword { get; set; } = null!;
  public string NewPassword { get; set; } = null!;
}